#!/usr/bin/env python
# -*- coding:utf-8 -*-
import base64
import binascii
import json
import urllib3
import os
import re
import time
import urllib
import uuid
from datetime import datetime
import hashlib
from hashlib import sha256, sha512, md5
import hmac
import random
import string
import execjs
import execjs._runner_sources as _runner_sources
from curl_cffi import requests
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad

# from pyDes import triple_des, PAD_PKCS5

local_node_runtime = execjs.ExternalRuntime(
    name="Node.js (V8) local",
    command='',
    encoding='UTF-8',
    runner_source=_runner_sources.Node
)
local_node_runtime._binary_cache = ['./node.exe']
local_node_runtime._available = True
execjs.register('local_node', local_node_runtime)
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


def get_current_time():
    return datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]


def parse_json(s):
    begin = s.find('{')
    end = s.rfind('}') + 1
    return json.loads(s[begin:end])


def parse_json_new(s):
    begin = s.find('(') + 1
    end = s.rfind('}') - 12
    return json.loads(s[begin:end])


def parse_msg(s):
    begin = s.find('(') + 1
    end = s.rfind(')')
    return json.loads(s[begin:end])


def parse_area_id(area):
    """解析地区id字符串：将分隔符替换为下划线 _
    :param area: 地区id字符串（使用 _ 或 - 进行分割），如 12_904_3375 或 12-904-3375
    :return: 解析后字符串
    """
    area_id_list = list(map(lambda x: x.strip(), re.split('_|-', area)))
    area_id_list.extend((4 - len(area_id_list)) * ['0'])
    return '_'.join(area_id_list)


def parse_sku_id(sku_ids):
    """将商品id字符串解析为字典

    商品id字符串采用英文逗号进行分割。
    可以在每个id后面用冒号加上数字，代表该商品的数量，如果不加数量则默认为1。

    例如：
    输入  -->  解析结果
    '123456' --> {'123456': '1'}
    '123456,123789' --> {'123456': '1', '123789': '1'}
    '123456:1,123789:3' --> {'123456': '1', '123789': '3'}
    '123456:2,123789' --> {'123456': '2', '123789': '1'}

    :param sku_ids: 商品id字符串
    :return: dict
    """
    if isinstance(sku_ids, dict):  # 防止重复解析
        return sku_ids

    sku_id_list = list(filter(bool, map(lambda x: x.strip(), sku_ids.split(','))))
    result = dict()
    for item in sku_id_list:
        if ':' in item:
            sku_id, count = map(lambda x: x.strip(), item.split(':'))
            result[sku_id] = count
        else:
            result[item] = '1'
    return result


def json_format(raw_msg):
    if isinstance(raw_msg, str):
        try:
            json.loads(raw_msg, encoding='utf-8')
            return True
        except ValueError:
            return False
    else:
        return False


# 抢购接口sk参数算法还原
def sk_sign(resp):
    list_data = []
    for value in resp['data'].values():
        list_data.append(value)

    if list_data[0] == 'cza':  # ok
        n = list_data[3][6:19].lower()
        UN = list_data[5][5:11]
    else:
        if list_data[0] == 'by':
            n = list_data[1][5:8]
            UN = list_data[2].replace('A', 'c').replace('a', 'c')  # ok
        else:
            if list_data[0] == 'cb':  # ok
                n = list_data[5][5:14]
                UN = list_data[2][2:13].upper()
            else:
                if list_data[0] == 'xa':  # ok
                    n = list_data[1][1:16]
                    UN = list_data[5][4:10]
                else:
                    if list_data[0] == 'ch':  # ok
                        n = list_data[3].upper()
                        UN = list_data[4][6:10].upper()
                    else:
                        if list_data[0] == 'cca':  # ok
                            n = list_data[2][14:19].lower()
                            UN = list_data[1][5:15].upper()
                        else:
                            if list_data[0] == 'ab':  # ok
                                n = list_data[4][10:18]
                                UN = list_data[5][2:13].lower()
                            else:
                                if list_data[0] == 'cbc':  # ok
                                    n = list_data[3][3:13].upper()
                                    UN = list_data[2][10:19].lower()  # list_data[2][14:23].lower()
                                else:
                                    n = list_data[5][5:14]
                                    UN = list_data[2][2:13].upper()
    sk = n + UN
    return sk


def get_hmacsha256(key, data):
    data = data.encode('utf-8')
    sign = hmac.new(key.encode('utf-8'), data, digestmod=sha256).hexdigest()
    return sign


def get_hmacsha512(key, data):
    data = data.encode('utf-8')
    sign = hmac.new(key.encode('utf-8'), data, digestmod=sha512).hexdigest()
    return sign


def get_hmacshamd5(key, data):
    data = data.encode('utf-8')
    sign = hmac.new(key.encode('utf-8'), data, digestmod=md5).hexdigest()
    return sign


def get_sha128(data):
    hash_object = hashlib.sha256(data.encode('utf-8'))
    hash_hex = hash_object.hexdigest()
    hash128 = hash_hex[:32]  # 取前 16 个字节（128位）作为结果
    return hash128


def get_sha256(data):
    s = hashlib.sha256()
    s.update(data.encode('utf-8'))
    b = s.hexdigest()
    return b


def get_sha512(data):
    s = hashlib.sha512()
    s.update(data.encode('utf-8'))
    b = s.hexdigest()
    return b


def get_md5(data):
    s = hashlib.md5()
    s.update(data.encode('utf-8'))
    b = s.hexdigest()
    return b


def get_date():
    now_time = time.strftime('%Y%m%d%H%M%S', time.localtime())
    sec = str(round(time.time() * 1000))
    return now_time + sec[10: 13], sec


def dict_json(d):
    '''python字典转json字符串, 去掉一些空格'''
    j = json.dumps(d).replace('": ', '":').replace(', "', ',"').replace(", {", ",{")
    return j


# 模拟安卓设备id
def android_id():
    brand = 'SAMSUNG'
    model = 'HUAWEI'
    os_version = '13'
    build_id = 'PPR1.180610.888'
    # 随机字符串
    rand_str = ''.join(random.choices('0123456789abcdef', k=32))
    # 计算ANDROID_ID
    device_id = brand + model + os_version + build_id
    android_id = hashlib.md5(device_id.encode()).hexdigest() + rand_str
    return android_id.upper()


# x-api-eid-token算法加密还原
def xapieidtokenEncrypt(n):
    n = json.dumps(n)
    """
     x-api-eid-token的需要用到的参数加密算法
        """
    js = """
        function encrypt(a){a=encodeURIComponent(a);var d="",b=0;do{var c=a.charCodeAt(b++),e=a.charCodeAt(b++),f=a.charCodeAt(b++),k=c>>2,c=(c&3)<<4|e>>4,h=(e&15)<<2|f>>6,g=f&63;isNaN(e)?h=g=64:isNaN(f)&&(g=64);d=d+"23IL<N01c7KvwZO56RSTAfghiFyzWJqVabGH4PQdopUrsCuX*xeBjkltDEmn89.-".charAt(k)+"23IL<N01c7KvwZO56RSTAfghiFyzWJqVabGH4PQdopUrsCuX*xeBjkltDEmn89.-".charAt(c)+"23IL<N01c7KvwZO56RSTAfghiFyzWJqVabGH4PQdopUrsCuX*xeBjkltDEmn89.-".charAt(h)+"23IL<N01c7KvwZO56RSTAfghiFyzWJqVabGH4PQdopUrsCuX*xeBjkltDEmn89.-".charAt(g)}while(b<a.length);return d+"/"};
        """
    ctx = execjs.get('local_node').compile(js)
    return ctx.call("encrypt", n)
    # n = json.dumps(n)
    # n = urllib.parse.quote(n)
    # m = ""
    # g = 0
    # while g < len(n):
    #     f = ord(n[g])
    #     g += 1
    #     d = ord(n[g]) if g < len(n) else 0
    #     g += 1
    #     a = ord(n[g]) if g < len(n) else 0
    #     g += 1
    #     b = f >> 2
    #     f = ((f & 3) << 4) | (d >> 4)
    #     e = ((d & 15) << 2) | (a >> 6)
    #     c = a & 63
    #     if math.isnan(d):
    #         e = c = 64
    #     elif math.isnan(a):
    #         c = 64
    #     m += "23IL<N01c7KvwZO56RSTAfghiFyzWJqVabGH4PQdopUrsCuX*xeBjkltDEmn89.-"[b] + \
    #          "23IL<N01c7KvwZO56RSTAfghiFyzWJqVabGH4PQdopUrsCuX*xeBjkltDEmn89.-"[f] + \
    #          "23IL<N01c7KvwZO56RSTAfghiFyzWJqVabGH4PQdopUrsCuX*xeBjkltDEmn89.-"[e] + \
    #          "23IL<N01c7KvwZO56RSTAfghiFyzWJqVabGH4PQdopUrsCuX*xeBjkltDEmn89.-"[c]
    # return m + "/"


# h5st算法v4.1 fp设备指纹算法
def get_fp41():
    js = """
         function fp41() {
  function e(t, e) {
    var n,
      i = [],
      a = t.length,
      o = r(t);
    try {
      for (o.s(); !(n = o.n()).done; ) {
        var s = n.value;
        if (Math.random() * a < e && (i.push(s), 0 == --e)) break;
        a--;
      }
    } catch (t) {
      o.e(t);
    } finally {
      o.f();
    }
    for (var c = "", l = 0; l < i.length; l += 1) {
      var u = (Math.random() * (i.length - l)) | 0;
      (c += i[u]), (i[u] = i[i.length - l - 1]);
    }
    return c;
  }
  function n(t, e) {
    for (var n = 0; n < e.length; n += 1) {
      var r = t.indexOf(e[n]);
      -1 !== r && (t = t.replace(e[n], ""));
    }
    return t;
  }
  function r(t, e) {
    var n,
      r,
      i = !0,
      a = !1;
    return {
      s: () => (n = t[Symbol.iterator]()),
      n: () => {
        var t = n.next();
        return (i = t.done), t;
      },
      e: (t) => {
        (a = !0), (r = t);
      },
      f: () => {
        try {
          i || null == n.return || n.return();
        } finally {
          if (a) throw r;
        }
      },
    };
  }
  function i(t) {
    for (var e = t["size"], n = t["num"], r = ""; e--; )
      r += n[(Math.random() * n.length) | 0];
    return r;
  }
  var a = "uct6d0jhqw",
    o = e(a, 6),
    s = (10 * Math.random()) | 0,
    c = n(a, o),
    l = {};
  (l["size"] = s), (l["num"] = c);
  for (
    var u =
        i(l) +
        o +
        i({
          size: 10 - s - 1,
          num: c,
        }) +
        s,
      d = u.split(""),
      f = d.slice(0, 14),
      h = d.slice(14),
      p = [];
    f.length > 0;

  )
    p.push((35 - parseInt(f.pop(), 36)).toString(36));
  return (p = p.concat(h)), p.join("");
}
    """
    ctx = execjs.get('local_node').compile(js)
    return ctx.call("fp41")


# h5st算法v3.1 fp设备指纹算法
def get_fp31():
    js = """
        function  fp31() {
    function t() {
        return 10 * Math.random() | 0
    }
    function e(t, e) {
        var n, i = [], a = t.length, o = r(t);
        try {
            for (o.s(); !(n = o.n()).done; ) {
                var s = n.value;
                if (Math.random() * a < e && (i.push(s),
                0 === --e))
                    break;
                a--
            }
        } catch (t) {
        } finally {
            o.f()
        }
        for (var c = "", l = 0; l < i.length; l++) {
            var u = Math.random() * (i.length - l) | 0;
            c += i[u],
                i[u] = i[i.length - l - 1]
        }
        return c
    }
    function n(t, e) {
        (null == e || e > t.length) && (e = t.length);
        for (var n = new Array(e), r = 0; r < e; r++)
            n[r] = t[r];
        return n
    }
    function r(t, e) {
        var r;
        if ("undefined" == typeof Symbol || null == t[Symbol.iterator]) {
            if (Array.isArray(t) || (r = function(t, e) {
                if (t) {
                    if ("string" == typeof t)
                        return n(t, e);
                    var r = Object.prototype.toString.call(t).slice(8, -1);
                    return "Object" === r && t.constructor && (r = t.constructor.name),
                        "Map" === r || "Set" === r ? Array.from(t) : "Arguments" === r || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r) ? n(t, e) : void 0
                }
            }(t)) || e && t && "number" == typeof t.length) {
                r && (t = r);
                var i = 0
                    , a = function() {};
                return {
                    s: a,
                    n: function() {
                        return i >= t.length ? {
                            done: !0
                        } : {
                            done: !1,
                            value: t[i++]
                        }
                    },
                    e: function(t) {
                        throw t
                    },
                    f: a
                }
            }
            throw new TypeError("Invalid attempt to iterate non-iterable instance.In order to be iterable, non-array objects must have a [Symbol.iterator]() method.")
        }
        var o, s = !0, c = !1;
        return {
            s: function() {
                r = t[Symbol.iterator]()
            },
            n: function() {
                var t = r.next();
                return s = t.done,
                    t
            },
            e: function(t) {
                c = !0,
                    o = t
            },
            f: function() {
                try {
                    s || null == r.return || r.return()
                } finally {
                    if (c)
                        throw o
                }
            }
        }
    }
    function i(t, e) {
        for (var n = 0; n < e.length; n++) {
            var r = t.indexOf(e[n]);
            -1 !== r && (t = t.replace(e[n], ""))
        }
        return t
    }
    function a(t) {
        for (var e = t.size, n = t.num, r = ""; e--; )
            r += n[Math.random() * n.length | 0];
        return r
    }
    for (var o = "0123456789", s = e(o, 3), c = t(), l = i(o, s), u = {
        size: c,
        num: l
    }, d = a(u) + s + a({
        size: 14 - (c + 3) + 1,
        num: l
    }) + c, f = d.split(""), h = []; f.length > 0; )
        h.push(9 - parseInt(f.pop() || ""));
    return h.join("")
}
    """
    ctx = execjs.get('local_node').compile(js)
    return ctx.call("fp31")


# h5st算法v4.2 fp设备指纹算法
def get_fp42():
    js = """
         function Vb(){for(var c={lqINR:"6|3|2|12|4|10|7|1|8|11|9|5|0",lUbpm:function(a,b,k){return a(b,k)},JftIS:function(a,b){return a(b)},vyQsK:function(a,b){return a-b},txuEl:function(a,b){return a>b}},g=c.lqINR.split("|"),f=0;;){switch(g[f++]){case "0":return h;case "1":var d=n.slice(14);continue;case "2":var e=10*Math.random()|0;continue;case "3":var b=c.lUbpm(Wb,k,4);continue;case "4":var a={};a.size=e;a.num=p;a=$b(a)+b+c.JftIS($b,{size:c.vyQsK(12,e)-1,num:p})+e;continue;case "5":var h=m.join("");continue;case "6":var k="6d0jhqw3pa";continue;case "7":var l=n.slice(0,14);continue;case "8":var m=[];continue;case "9":m=m.concat(d);continue;case "10":var n=a.split("");continue;case "11":for(;c.txuEl(l.length,0);)m.push(c.vyQsK(35,parseInt(l.pop(),36)).toString(36));continue;case "12":var p=c.lUbpm(Kb,k,b);continue}break}}function Wb(c,g){var f,d={PfGok:function(a,b){return a(b)},bAOTZ:function(a,b){return a<b},qPWEw:function(a,b){return a*b},rejmK:function(a,b){return a==b},xJXfP:function(a,b){return a<b},SFDpu:function(a,b){return a*b}},e=[],b=c.length,a=d.PfGok(Fb,c);try{for(a.s();!(f=a.n()).done;){var h=f.value;if(d.bAOTZ(d.qPWEw(Math.random(),b),g)&&(e.push(h),d.rejmK(--g,0)))break;b--}}catch(k){a.e(k)}finally{a.f()}f="";for(b=0;d.xJXfP(b,e.length);b++)a=0|d.SFDpu(Math.random(),e.length-b),f+=e[a],e[a]=e[e.length-b-1];return f}function Fb(c,g){for(var f={vKRae:"1|0|4|3|2",PahBQ:function(a,b){return a(b)},Duklj:function(a,b){return a!=b},nbXWH:function(a,b){return a(b)},FMotf:function(a,b){return a&&b},meAhl:"number",ItyWq:"Invalid attempt to iterate non-iterable instance.\r\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."},d=f.vKRae.split("|"),e=0;;){switch(d[e++]){case "0":var b;continue;case "1":var a={zfUkm:function(a,b){return f.PahBQ(a,b)},CyNpV:function(a,b){return f.Duklj(a,b)}};continue;case "2":return{s:function(){b=c[Symbol.iterator]()},n:function(){var a=b.next();return k=a.done,a},e:function(a){l=!0;h=a},f:function(){try{!k&&a.CyNpV(b["return"],null)&&b["return"]()}finally{if(l)throw h;}}};case "3":var h,k=!0,l=!1;continue;case "4":continue}break}}function Kb(c,g){for(var f={VQOZS:function(b,a){return b<a},SEAHc:function(b,a){return b(a)},iEaXW:function(b,a){return b!==a}},d=0;f.VQOZS(d,g.length);d++){var e=c.indexOf(g[d]);f.iEaXW(e,-1)&&(c=c.replace(g[d],""))}return c}function $b(c){for(var g={XHxlS:"1|2|4|0|3",hjsnI:function(a,b){return a|b}},f=g.XHxlS.split("|"),d=0;;){switch(f[d++]){case "0":for(;e--;)h+=a[g.hjsnI(Math.random()*a.length,0)];continue;case "1":var e=c.size,b=c.num;continue;case "2":var a=b;continue;case "3":return h;case "4":var h="";continue}break}};
    """
    ctx = execjs.get('local_node').compile(js)
    return ctx.call("Vb")


# h5st算法v4.3 fp设备指纹算法
def get_fp43():
    js = """
    function oA(){for(var a={YhBOI:function(a,b,c){return a(b,c)},MkSDb:function(a,b){return a+b},FzFhf:function(a,b){return a(b)},tdLUG:function(a,b){return a-b},nmMmO:function(a,b){return a>b}},h="11 2 0 10 4 7 3 12 9 6 5 1 8".split(" "),c=0;;){switch(h[c++]){case "0":var d=iA();continue;case "1":var g=b.join("");continue;case "2":var e=a.YhBOI(aA,m,3);continue;case "3":var f=l.slice(0,10);continue;case "4":var k={};k.size=d;k.num=n;k=a.MkSDb(cA(k)+e+a.FzFhf(cA,{size:a.tdLUG(a.tdLUG(13,d),1),num:n}),d);continue;case "5":b=b.concat(p);continue;case "6":for(;a.nmMmO(f.length,0);)b.push((35-parseInt(f.pop(),36)).toString(36));continue;case "7":var l=k.split("");continue;case "8":return g;case "9":var b=[];continue;case "10":var n=sA(m,e);continue;case "11":var m="kl9i1uct6d";continue;case "12":var p=l.slice(10);continue}break}}function aA(a,h){var c={UsXkK:function(a,b){return a<b},tNBcm:function(a,b){return a*b},TVKLo:function(a,b){return a|b},tWmfP:function(a,b){return a-b}},d=[],g=a.length,e,f=rA(a);try{for(f.s();!(e=f.n()).done;){var k=e.value;if(c.UsXkK(c.tNBcm(Math.random(),g),h)&&(d.push(k),0==--h))break;g--}}catch(l){f.e(l)}finally{f.f()}g="";for(e=0;c.UsXkK(e,d.length);e++)f=c.TVKLo(Math.random()*c.tWmfP(d.length,e),0),g+=d[f],d[f]=d[c.tWmfP(c.tWmfP(d.length,e),1)];return g}function rA(a,h){for(var c={Jerdn:function(a,b){return a(b)},cvAXC:function(a,b){return a!=b}},d=["1","3","2","0","4"],g=0;;){switch(d[g++]){case "0":var e,f=!0,k=!1;continue;case "1":var l={McmJv:function(a,b){return c.Jerdn(a,b)},MCkIn:function(a,b){return c.cvAXC(a,b)}};continue;case "2":continue;case "3":var b;continue;case "4":return{s:function(){b=a[Symbol.iterator]()},n:function(){var a=b.next();return f=a.done,a},e:function(a){k=!0;e=a},f:function(){try{!f&&l.MCkIn(b["return"],null)&&b["return"]()}finally{if(k)throw e;}}}}break}}function iA(){var a={EESIU:function(a,c){return a|c},vMfiK:function(a,c){return a*c}};return a.EESIU(a.vMfiK(Math.random(),10),0)}function sA(a,h){for(var c={ggIPa:function(a,c){return a!==c}},d=0;d<h.length;d++){var g=a.indexOf(h[d]);c.ggIPa(g,-1)&&(a=a.replace(h[d],""))}return a}function cA(a){for(var h={CysRZ:"4|2|1|3|0",DoNne:function(a,b){return a|b},ybJbA:function(a,b){return a*b}},c=h.CysRZ.split("|"),d=0;;){switch(c[d++]){case "0":return g;case "1":var g="";continue;case "2":var e=k;continue;case "3":for(;f--;)g+=e[h.DoNne(h.ybJbA(Math.random(),e.length),0)];continue;case "4":var f=a.size,k=a.num;continue}break}};
    """
    ctx = execjs.get('local_node').compile(js)
    return ctx.call("oA")


def generate_random_string(length):
    # 从字母表中选择字符，并将其组合成一个随机字符串
    letters = string.ascii_letters + string.digits
    return ''.join(random.choice(letters) for i in range(length))


# 京东触屏端(m)端提交订单body signStr参数加密算法还原
def getSignStr(data):
    sorted_keys = sorted(data.keys())
    result = '&'.join(str(data[key]) for key in sorted_keys if data[key] != '')
    result = result.replace(' ', '').replace('\'', '\"')
    return get_hmacshamd5('xtl_sqg_mall-^&*-damai_(789)_@#$', result)


def generate_sequence_id():
    try:
        str_val = md5_hash(str(time.time()) + str(os.getpid()) + str(uuid.uuid4())) + generate_random_str()
        sequence_id = str_val + calculate_checksum(str_val)
        return sequence_id
    except Exception:
        return ""


def generate_random_str():
    try:
        return ''.join([random.choice('0123456789abcdef') for _ in range(4)])
    except Exception:
        return ""


def md5_hash(str_val):
    try:
        m = hashlib.md5()
        m.update(str_val.encode('utf-8'))
        return m.hexdigest()
    except Exception:
        return ""


def calculate_checksum(str_val):
    try:
        if str_val and len(str_val) == 36:
            i2 = 0
            i3 = 0
            for i4 in range(len(str_val)):
                if i4 % 2 == 0:
                    i2 += int(str_val[i4], 16)
                else:
                    temp = int(str_val[i4], 16) * 2
                    i3 += temp if temp < 16 else (temp // 16) + (temp % 16)
            i5 = (i2 + i3) % 16
            return "0" if i5 == 0 else hex(16 - i5)[2:]
        return "x"
    except Exception:
        return "x"


def deal_b2(str, str2, str3):
    switch = {
        "01": 0,
        "02": 1,
        "03": 2,
        "04": 3,
        "05": 4,
        "06": 5
    }
    c2 = switch.get(str, 65535)
    if c2 in [0, 1, 2]:
        return e(str2, str3)
    else:
        return d(str2, str3)


# def d(str, str2):
#     print(str2)
#     bytes = str2.encode()
#     if len(bytes) % 16 != 0:
#         bytes = pad(bytes, 16)
#     try:
#         cipher = AES.new(bytes, AES.MODE_CBC, iv=b'0000000000000000')
#         return cipher.encrypt(pad(str.encode(), AES.block_size))
#     except Exception as e:
#         print(e)
#         return None
def d(data, key):
    # 确保密钥长度符合AES的要求（128/192/256位）
    if len(key) % 16 != 0:
        key += '\0' * (16 - len(key) % 16)

    # 初始化密钥和IV（初始向量）
    key_bytes = key.encode('utf-8')
    iv = b'0000000000000000'

    # 创建AES加密器实例
    cipher = AES.new(key_bytes, AES.MODE_CBC, iv)

    # 对数据进行PKCS7填充
    padded_data = pad(data.encode('utf-8'), AES.block_size)

    # 返回加密后的数据
    return cipher.encrypt(padded_data)


def e(str, str2):
    print('3DES加密')
    bytes = str2.encode()
    if len(bytes) % 24 != 0:
        bArr = bytearray((len(bytes) // 24 + 1) * 24)
        bArr[:len(bytes)] = bytes
        bytes = bArr

    try:
        secretKeySpec = triple_des(key=bytes, padmode=PAD_PKCS5, IV="".encode())
        return secretKeySpec.encrypt(str.encode())
    except Exception as e:
        print(e)
        return None


def deal_c2_str_d2(s, s2, s3):
    switch = {
        '01': lambda: a_func_two_args(s, s2),
        '02': lambda: b_func_two_args(s, s2),
        '03': lambda: c_func_two_args(s, s2),
        '04': lambda: a_func_two_args(s, s2),
        '05': lambda: b_func_two_args(s, s2),
        '06': lambda: c_func_two_args(s, s2),
    }
    return switch.get(s3, lambda: "")()


# def a_func(s):
#     return int(re.sub("[^0-9]", "", s))
def a_func(s):
    s = re.sub("[^0-9]", "", s)
    return int(s) if s else 0


def b_func(s):
    return [int(s[i]) if s[i].isdigit() else ord(s[i]) % 10 for i in range(1, len(s), 2)]


def c_func(s):
    return [int(s[i]) if s[i].isdigit() else ord(s[i]) % 10 for i in range(0, len(s), 2)]


def d_func(s):
    return [int(s[i]) if s[i].isdigit() else ord(s[i]) % 10 for i in range(5)]


def e_func(s):
    return [int(s[i]) if s[i].isdigit() else ord(s[i]) % 10 for i in range(len(s) - 5, len(s))]


def a_func_two_args(s, s2):
    a2 = a_func(s)
    l2 = 0
    b2 = b_func(s2)
    for num in b2:
        l2 = int(str(l2) + str(num))
    return str(abs(a2 - l2))


def b_func_two_args(s, s2):
    c2 = c_func(s)
    b2 = b_func(s2)
    if len(c2) == 5 and len(b2) == 6:
        sb = str(abs(b2[0]))
        for i2 in range(1, len(c2)):
            sb += str(abs(c2[i2] - b2[i2]))
        return sb
    return ""


def c_func_two_args(s, s2):
    d2 = d_func(s)
    e2 = e_func(s2)
    sb = ""
    for i2 in range(len(d2)):
        sb += str(abs(d2[i2] - e2[i2]))
    return sb


def generate_random_hash(length=12):
    """ Generates a random hash of specified length """
    random_number = str(random.randint(1000000000, 9999999999))
    hash_object = hashlib.sha256(random_number.encode())
    return hash_object.hexdigest()[:length]


def construct_data_info(wifi_mac, uuid, sequence_id, installid):
    """ Constructs the data string using the given IMEI and other random components """
    jdkey = f"-{wifi_mac}-{uuid}-{sequence_id}"
    # installationid = generate_random_hash(32)  # Assuming a 64 length hash for installation id
    # installationid='0a686bcf0d89dddd06a6fe38fc782c26'
    data = {
        "appname": "com.jingdong.app.mall_com.jma.track",
        "appid": "100",
        "client": "android",
        "jdkey": "jidwhzqalpk" + base64.b64encode(jdkey.encode("utf-8")).decode(),
        "installtionid": installid,
        "dataset": ["alterationinfo", "fixedinfo"],
        "sdkversion": "2.5.9",
        "clientversion": "12.3.1",
        "body": [{"appsign": "android_12.3.1_4fbb30eb7b7166119bd25e41eddeee2f", "head": "", "info": ""}]
    }

    # print(data)
    # Constructing the JSON string
    json_string = str(data).replace("'", '"')
    json_string = json_string.replace(' ', '')
    # URL encoding the JSON string
    encoded_data = urllib.parse.quote(json_string, safe='')
    # _也url编码
    encoded_data = encoded_data.replace('_', '%5F')

    return "content=" + encoded_data


def construct_data(wifi_mac, uuid, sequence_id):
    """ Constructs the data string using the given IMEI and other random components """
    jdkey = f"-{wifi_mac}-{uuid}-{sequence_id}"
    installationid = generate_random_hash(32)  # Assuming a 64 length hash for installation id
    # installationid='0a686bcf0d89dddd06a6fe38fc782c26'
    data = {
        "appname": "com.jingdong.app.mall_com.jma.track",
        "whwswswws": "",
        "jdkey": "jidwhzqalpk" + base64.b64encode(jdkey.encode("utf-8")).decode("utf-8"),
        "installtionid": installationid,
        "appid": "100",
        "dataset": ["alterationinfo", "fixedinfo"],
        "sdkversion": "4.2.2",
        "clientversion": "13.2.9",
        "client": "android",
        "body": {"appsign": "android_13.2.9_4fbb30eb7b7166119bd25e41eddeee2f", "head": "", "info": ""}
    }

    # print(data)
    # Constructing the JSON string
    json_string = str(data).replace("'", '"')
    json_string = json_string.replace(' ', '')
    # URL encoding the JSON string
    encoded_data = urllib.parse.quote(json_string, safe='')
    # _也url编码
    encoded_data = encoded_data.replace('%2F', '%5C%2F')
    return "content=" + encoded_data, installationid


def construct_data2(wifi_mac, uuid, sequence_id, installationid, wss):
    """ Constructs the data string using the given IMEI and other random components """
    jdkey = f"-{wifi_mac}-{uuid}-{sequence_id}"
    # installationid='0a686bcf0d89dddd06a6fe38fc782c26'
    data = {
        "appname": "com.jingdong.app.mall_com.jma.track",
        "appid": 100,
        "whwswswws": wss,
        "jdkey": "jidwhzqalpk" + base64.b64encode(jdkey.encode("utf-8")).decode("utf-8"),
        "installtionid": installationid,
        "client": "android",
        "body": {"appsign": "android_12.3.1_4fbb30eb7b7166119bd25e41eddeee2f", "head": "",
                 "info": "lrxM8JkimTAduzTH7ZfAqRpxp3oeqghkUGHy4J/scNc7vMoIlpMCm64yIePBmvqUsQLxcYXFt8vOQzHH+GH5U/v4w5jWHor43xc4ITCS61NXpRTsSa7dAF6eX+znCJt7VzULBgUsEKMIlV3e9afv+aYbpjy+iKUxav9FF7J0xP3lTozn0TrJi5lXYkCau8FCNy/ToeUtFk/N7n2pJDsOttq1k4tKGpSG4xsoYJhI7cKA2dOD6+/Czdsy17vb/8BYPPTEz+0XKHcLfkLj1VyWvfec+tM/Z82uo7qavadpvgOwj01d0mHQQ6/Rye53SnEvV4FwkRHhWdgxlsUI9TSBCuX3aEbEgFAkTDz2AWhhML37BuAOSWYqQTWtarGu2BwfgLFtt/QRc+dfPLcQphRqevjEGNQ67ahcPHHVp2OsUMp/1db3DYh6hhWwnSjN3NRIvGOgM5WaPONyIRv1RpIPi76zEh+htMDoJtaADtQQDUewpEuIAMCXYljWQO44rYbeb8rb1Eyw9pSz43MrSCPf07vkICOnc7mG6mjxxiAliQt/oWizCuyd4b7pSz8zb6rvRFR0R0S+0uDHJxhXb1OXXyqJHa90lhdJCzcuuBLyKSwEiJssA==",
                 "functionId": "alterationinfo", "sdkversion": "2.5.9"}
    }

    # print(data)
    # Constructing the JSON string
    json_string = str(data).replace("'", '"')
    json_string = json_string.replace(' ', '')
    # URL encoding the JSON string
    encoded_data = urllib.parse.quote(json_string, safe='')
    # _也url编码
    encoded_data = encoded_data.replace('_', '%5F')

    return "content=" + encoded_data


def pkcs7padding(text):
    """
    明文使用PKCS7填充
    """
    bs = 16
    length = len(text)
    bytes_length = len(text.encode('utf-8'))
    padding_size = length if (bytes_length == length) else bytes_length
    padding = bs - padding_size % bs
    padding_text = chr(padding) * padding
    # self.coding = chr(padding)
    return text + padding_text


def random_num(digits):
    return ''.join(str(random.choice(range(10))) for _ in range(digits))


def random_str(num):
    """
    随机字符串
    """
    random_string = ""
    base_str = "ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789"
    length = len(base_str) - 1
    for i in range(num):
        random_string += base_str[random.randint(0, length)]
    return random_string


def random_hex(num):
    """
    随机字符串
    """
    random_string = ""
    base_str = "abcdef0123456789"
    length = len(base_str) - 1
    for i in range(num):
        random_string += base_str[random.randint(0, length)]
    return random_string


def get_random_mac():
    """
    随机mac地址
    """
    mac = [0x52, 0x54, 0x00,
           random.randint(0x00, 0x7f),
           random.randint(0x00, 0xff),
           random.randint(0x00, 0xff)]
    return ':'.join(map(lambda x: "%02x" % x, mac))


def get_imei():
    """
    随机imei
    """
    imei = "86" + random_num(13)
    return imei


def get_js(data):
    result = aes_encode(bytes("a*cj&fc-{47yx!//", "utf-8"), bytes("0102030405060708", "utf-8"), data)
    return result


def aes_encode(key_bytes, iv_bytes, content):
    """
    AES加密
    key,iv使用同一个
    模式cbc
    填充pkcs7
    :param key: 密钥
    :param content: 加密内容
    :return:
    """
    # key_bytes = bytes(key, encoding='utf-8')
    # iv_bytes = bytes(iv, encoding='utf-8')
    cipher = AES.new(key_bytes, AES.MODE_CBC, iv_bytes)
    # 处理明文
    content_padding = pkcs7padding(content)
    # 加密
    aes_encode_bytes = cipher.encrypt(bytes(content_padding, encoding='utf-8'))
    # 重新编码
    result = binascii.b2a_base64(aes_encode_bytes)  # b
    return str(result, "utf-8")


# app的eid获取
def get_eid(android_id):
    timestamp = time.time()
    wallpaper = hashlib.md5(str(timestamp).encode()).hexdigest()
    fontListMD5 = wallpaper
    appListMD5 = wallpaper
    bssid = get_random_mac().upper()
    system_version = "4.4.4"
    # serialno ＝ 取文本左边 (到大写 (取数据摘要 (到字节集 (imei))), 6)
    imei = get_imei()
    serialno = 'FA' + hashlib.md5(imei.encode()).hexdigest()[:10].upper()
    # android_id ＝ 取文本左边 (取数据摘要 (到字节集 (imei)), 16)
    # android_id = random_hex(16)
    # mac ＝ 到大写 (get_mac ())
    mac = get_random_mac().upper()
    link_speed = "1" + random_num(2)
    gateway = "1" + random_num(7)
    data = {
        "deviceInfo": {
            "timestamp": int(timestamp),
            "fpVersion": "5.4.5",
            "platform": "android",
            "ssid": "<unknown ssid>",
            "bssid": bssid,
            "rssi": -31,
            "link_speed": "1" + random_num(2),
            "gateway": gateway,
            "netmask": 0,
            "ip_add": 185219939,
            "wifiable": 1,
            "dns2": "0.0.0.0",
            "dns1": "192.168.50.2",
            "bluetoothAddress": "",
            "bluetoothName": "Pixel",
            "netOperator": "",
            "cellId": -1,
            "wifiList": "[]",
            "local_ip": "196.168.50.2",
            "networkType": "wifi",
            "w_m_a": "",
            "sm": "",
            "timeZone": "Asia/Shanghai",
            "language": "zh",
            "package_name": "com.jingdong.app.mall",
            "appName": "京东",
            "client_version": 88569,
            "versionName": "",
            "sig_hash": -1835375315,
            "resolution": "",
            "dpi": 480,
            "p_model": "ALN-AL80",
            "p_brand": "HUAWEI",
            "p_device": "sailfish",
            "p_manuf": "Google",
            "p_name": "sailfish",
            "p_cpuabi": "arm64-v8a",
            "hardware": "",
            "sdk_version": 25,
            "system_version": system_version,
            "romSize": 19479,
            "imei": "",
            "serialno": serialno,
            "android_id": android_id,
            "mac": mac,
            "realResolution": "",
            "fingerprints": "",
            "romSurplus": "0.211",
            "fontScale": "1.0",
            "userAgent": "",
            "fontListMd5": fontListMD5,
            "wallpaper": "",
            "appListMd5": appListMD5,
            "appListPart": "[]",
            "fingerprintFromJni": "",
            "modelFromJni": "Pixel",
            "permission": "00100111",
            "emulator": {},
            "brightness": 66,
            "brightnessMode": 1,
            "oaid": "",
            "dk": {
                "code": "0000000",
                "des": ""
            },
            "root": 0,
            "appList": [],
            "fingerprintCustom": ""
        }
    }
    data = json.dumps(data, separators=(',', ':'))
    dataa = get_js(data)

    # dataa='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'
    url = 'https://eidv2.jd.com/android/v2/geteid.png'
    header = {
        'Accept': 'application/json',
        'versionc': '5.4.4c',
        'Content-type': 'application/json;charset=utf-8',
        'Charsetc': 'Charset',
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 8.1.0; Pixel Build/OPM1.171019.011)',
        'Hostc': 'Host',
        'Connection': 'Keep-Alive'

    }
    while True:
        try:
            resp = requests.post(url, headers=header, data=dataa, verify=False)
            eid = resp.json()['data']['eid']
            if eid == '':
                time.sleep(2)
                continue
            return eid
        except:
            pass
